<template>
    <div class="product-form">
        <h3>修改产品档案</h3>
        <el-form :model="formData">
            <!-- 产品基本信息 -->
            <el-row>
                <el-col :span="6">
                    <el-form-item label="产品编码">
                        <el-input v-model="formData.productCode" readonly placeholder="请输入产品编码" />
                    </el-form-item>
                </el-col>
                <el-col :span="12"></el-col>
                <el-col :span="6">
                    <el-form-item label="产品名称">
                        <el-input v-model="formData.cp_name" placeholder="请输入产品名称" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="产品品牌">
                        <el-input v-model="formData.pp_name" placeholder="请输入产品品牌" />
                    </el-form-item>
                </el-col>
                <el-col :span="12"></el-col>
                <el-col :span="6">
                    <el-form-item label="产品分类">
                        <el-select v-model="formData.cp_fl" placeholder="请选择产品分类">
                            <el-option v-for="type in cpfl" :key="type.dictionary_id" :label="type.dictionary_name"
                                :value="type.dictionary_id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="产品型号">
                        <el-input v-model="formData.cp_xh" placeholder="请输入产品型号" />
                    </el-form-item>
                </el-col>
                <el-col :span="12"></el-col>
                <el-col :span="6">
                    <el-form-item label="产品单位">
                        <el-select v-model="formData.dw_code" placeholder="请选择产品单位">
                            <el-option v-for="type in dwOptions" :key="type.dw_code" :label="type.dw_name"
                                :value="type.dw_code" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="BOM">
                        <el-input v-model="formData.bom_code" placeholder="请选择BOM" />
                    </el-form-item>
                </el-col>
                <el-col :span="12"></el-col>
                <el-col :span="6">
                    <el-form-item label="产品类型">
                        <el-select v-model="formData.cp_lx" placeholder="请选择产品类型">
                            <el-option v-for="type in cplx" :key="type.dictionary_id" :label="type.dictionary_name"
                                :value="type.dictionary_id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 产品属性 -->
            <h3>产品属性</h3>
            <el-table :data="formData.attributes" border>
                <el-table-column label="序号" width="80">
                    <template #default="{ $index }">
                        {{ $index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column prop="sx_name" label="属性名称"></el-table-column>
                <el-table-column prop="sx_zhi" label="属性值">
                    <template #default="{ row }">
                        <el-select v-model="row.sx_zhi" placeholder="请选择属性值">
                            <el-option label="值1" value="值1"></el-option>
                            <el-option label="值2" value="值2"></el-option>
                            <el-option label="值3" value="值3"></el-option>
                            <el-option label="值4" value="值4"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="{ row }">
                        <el-button type="text" @click="removeAttribute(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-button type="primary" @click="addAttribute">添加属性</el-button>
            <!-- 产品文档 -->
            <h3>产品文档</h3>
            <el-table :data="formData.documents" border>
                <el-table-column label="序号" width="80">
                    <template #default="{ $index }">
                        {{ $index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="文档名称">
                    <template #default="{ row }">
                        <el-input v-model="row.cpwd_name" placeholder="请输入文档名称" />
                    </template>
                </el-table-column>
                <el-table-column label="文档链接">
                    <template #default="{ row }">
                        <el-input v-model="row.cpwd_lb" placeholder="请输入文档链接" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="{ row }">
                        <el-button type="text" @click="removeDocument(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-button type="primary" @click="addDocument">添加文档</el-button>
            <!-- 产品图片 -->
            <h3>产品图片</h3>
            <el-table :data="formData.images" border>
                <el-table-column label="序号" width="80">
                    <template #default="{ $index }">
                        {{ $index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="图片名称">
                    <template #default="{ row }">
                        <el-input v-model="row.cptp_name" placeholder="请输入图片名称" />
                    </template>
                </el-table-column>
                <el-table-column label="图片链接">
                    <template #default="{ row }">
                        <el-input v-model="row.cptp_zhi" placeholder="请输入图片链接" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="{ row }">
                        <el-button type="text" @click="removeImage(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-button type="primary" @click="addImage">添加图片</el-button>

            <!-- 操作按钮 -->
            <el-row justify="end" style="margin-top: 20px;">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save">保 存</el-button>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';

export default {
    setup() {
        // 表单数据
        const formData = ref({
            productCode: '',
            cp_name: '',
            pp_code:'',
            pp_name: '',
            cp_fl: '',
            cp_xh: '',
            dw_code: '',
            bom_code: '',
            cp_lx: '',
            cp_lxname:'',
            update_by:'',
            documents: [],
            images: [],
            attributes: []
        });
        const router = useRouter();
        const route = useRoute();

        // 存储各类数据
        const dwOptions = ref([]);
        const cpfl = ref([]);
        const cplx = ref([]);

        // 集中管理 API URL
        const API_URLS = {
            product: `/api/BD_CP/GetBD_CPcp_code`,
            attributes: '/api/BD_CPSX/Getcpsxname',
            images: '/api/BD_CPTP/Getcptpe',
            documents: '/api/BD_CPWD/Getcpwd',
            category: '/api/Dict/GetOneDict?id=7',
            type: '/api/Dict/GetOneDict?id=9',
            units: '/api/DW/GetOneDW'
        };

        // 生命周期钩子，组件挂载时执行
        onMounted(() => {
            formData.value.productCode = route.query.productId;
            formData.value.update_by=sessionStorage.getItem('u');
            fetchData();
        });

        // 取消操作
        const cancel = () => {
            router.push('/Product');
        };

        // 并行获取数据
        const fetchData = async () => {
            const cpCode = formData.value.productCode;
            const requests = [
                { url: API_URLS.product, params: { cp_code: cpCode } },
                { url: API_URLS.attributes, params: { code: cpCode } },
                { url: API_URLS.images, params: { code: cpCode } },
                { url: API_URLS.documents, params: { code: cpCode } },
                { url: API_URLS.category },
                { url: API_URLS.type },
                { url: API_URLS.units }
            ];

            try {
                const responses = await Promise.all(
                    requests.map(({ url, params }) => axios.get(url, { params }))
                );

                const [
                    productRes,
                    attrRes,
                    imgRes,
                    docRes,
                    categoryRes,
                    typeRes,
                    unitRes
                ] = responses;

                // 修正文档数据赋值
                formData.value.documents = docRes.data;
                formData.value.images = imgRes.data;
                formData.value.attributes = attrRes.data;
                cpfl.value = categoryRes.data;
                cplx.value = typeRes.data;
                dwOptions.value = unitRes.data;

                if (productRes.data) {
                    formData.value = { ...formData.value, ...productRes.data };
                }
            } catch (error) {
                console.error('Error fetching tableData:', error);
                ElMessage.error('数据获取失败');
            }
        };

        const addAttribute = () => {
            formData.value.attributes.push({ sx_name: '', sx_zhi: '' });
        };

        const removeAttribute = (row) => {
            const index = formData.value.attributes.indexOf(row);
            if (index > -1) {
                formData.value.attributes.splice(index, 1);
            }
        };

        const addDocument = () => {
            formData.value.documents.push({ cpwd_name: '', cpwd_lb: '' });
        };

        const removeDocument = (row) => {
            const index = formData.value.documents.indexOf(row);
            if (index > -1) {
                formData.value.documents.splice(index, 1);
            }
        };

        const addImage = () => {
            formData.value.images.push({ cptp_name: '', cptp_zhi: '' });
        };

        const removeImage = (row) => {
            const index = formData.value.images.indexOf(row);
            if (index > -1) {
                formData.value.images.splice(index, 1);
            }
        };

        // 保存数据
        const save = async () => {
            try {
                await axios.put(`/api/BD_CP/UpdateCP`, formData.value);
                ElMessage.success('保存成功');
            } catch (error) {
                console.error('Error saving data:', error);
                ElMessage.error('保存失败');
            }
        };

        return {
            formData,
            addAttribute,
            removeAttribute,
            addDocument,
            removeDocument,
            addImage,
            removeImage,
            save,
            cancel,
            cpfl,
            cplx,
            dwOptions
        };
    },
};
</script>

<style scoped>
.product-form {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.el-form {
    flex: 1;
    overflow-y: auto;
}
</style>